package com.pai4j.zwiki.websocket.config;

import com.pai4j.zwiki.websocket.handler.ZWikiNotificationWebSocketHandler;
import com.pai4j.zwiki.websocket.interceptor.ZWikiWebSocketInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * ZWiki WebSocket配置
 * 
 * 提供实时消息推送能力，用于：
 * 1. 任务状态实时更新
 * 2. 队列位置实时通知
 * 3. 进度实时推送
 * 4. 任务完成/失败通知
 *
 * WebSocket端点：
 * - /zwiki-service/ws/notification/{userId}  - 任务通知频道
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Configuration
@EnableWebSocket
@RequiredArgsConstructor
public class ZWikiWebSocketConfig implements WebSocketConfigurer {

    /**
     * ZWiki任务通知WebSocket路径
     * 客户端连接示例：ws://localhost:8096/zwiki-service/ws/notification/123
     */
    private static final String NOTIFICATION_WEBSOCKET_PATH = "/zwiki-service/ws/notification/{userId}";

    /**
     * 注册WebSocket处理器
     *
     * @param registry WebSocket处理器注册表
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        /**
         * 注册ZWiki任务通知WebSocket端点
         * - 处理路径：/zwiki-service/ws/notification/{userId}
         * - 允许跨域：所有来源
         * - 拦截器：提取userId参数
         */
        registry.addHandler(zWikiNotificationWebSocketHandler(), NOTIFICATION_WEBSOCKET_PATH)
                .setAllowedOrigins("*")  // 允许所有跨域（生产环境应配置具体域名）
                .addInterceptors(new ZWikiWebSocketInterceptor());
    }

    /**
     * 创建ZWiki通知WebSocket处理器Bean
     *
     * @return ZWiki通知WebSocket处理器实例
     */
    @Bean
    public ZWikiNotificationWebSocketHandler zWikiNotificationWebSocketHandler() {
        return new ZWikiNotificationWebSocketHandler();
    }
}

